/*
 * @ author madman 
 * @ use 广告管理控制器
 */

const AdvertisingModel = require('../../models/marketing/advertising.model');
const UploadModel = require('../../models/upload/upload.model');
const Utils = require('../utils');
const path = require('path');
const qiniu = require('../../middleware/qiniu');
class AdvertisingController {
    // 添加
    async add(ctx) {
        const _body = ctx.request.body
        const _params = {
            name: _body.name,
            ad_type: _body.ad_type,
            img_path: _body.img_path,
            img_id: _body.img_id,
            link: _body.link,
            sort: _body.sort,
            describe: _body.describe,
            number: _body.number
        }
        const result = await AdvertisingModel.create(_params);
        if (result) {
            return ctx.success({ msg: '添加成功' });
        } else {
            return ctx.error({ msg: '添加失败' });
        }
    }
    // 更新
    async update(ctx) {
        const _body = ctx.request.body
        const _params = Utils._params(_body)
        _params.updataAt = new Date()
        const result = await AdvertisingModel.update({ _id: _body._id }, { $set: _params });
        if (result) {
            return ctx.success({ msg: '更新成功' });
        } else {
            return ctx.error({ msg: '更新失败' });
        }
    }
    // 删除
    async delete(ctx) {
        const _id = ctx.query.id
        const Advertising = await AdvertisingModel.findOne({ _id: _id });
        const thumb = await UploadModel.findById({ _id: Advertising.img_id });
        if (thumb) {
            //遍历删除七牛云上的图片
            thumb.imgPath.forEach(item => {
                //images加哈希后的路径为KEY才能删除云上的内容
                const fileName = path.win32.basename(item.url);
                qiniu.client.delete('images/' + fileName, function(err) {
                    return ctx.success({ msg: '删除失败', err: err });
                })
            })
            //移除数据库保存的路径
            await UploadModel.remove({ _id: Advertising.img_id });
        } else {
            return ctx.error({ msg: '组图删除失败' });
        }
        const result = await AdvertisingModel.remove({ _id: _id });
        if (result) {
            return ctx.success({ msg: '删除成功' });
        } else {
            return ctx.error({ msg: '删除失败' });
        }
    }
    // 获取带分页列表
    async list(ctx) {
        const options = {
            name: 'marketing/advertising',
            type: 'page',
            sortType: 'sort',
            sortVal: '1'
        }
        if (ctx.query.ad_type) {
            options.findField = {
                ad_type: ctx.query.ad_type
            }
        }
        let result = await Utils.getPageList(ctx, options)
        if (result) {
            return ctx.success({
                data: result,
                msg: '查询成功'
            });
        }
    }

}

export default new AdvertisingController;